//
//  LSZSearchUISetVC.m
//  JKFuYinProject
//
//  Created by 九酷 on 2017/12/14.
//  Copyright © 2017年 LC. All rights reserved.
//

#import "LSZSearchUISetVC.h"

@interface LSZSearchUISetVC ()
{
   LSZEmptyDataVC * vcResults;
}
@end

@implementation LSZSearchUISetVC
-(void)viewWillAppear:(BOOL)animated
{
    if (self.tableViewResults.hidden == NO && self.mutArrayContent.count>0) {
        [self.tableViewResults reloadData];
    }else{
        [LSZRequestResolutionDic initWithSearchKey:^(BOOL isOk, NSString * str, LSZSearchKeyManager * manager) {
            if (isOk == YES) {
                self.SearchKeyMg = manager;
                [self.collectionView reloadData];
            }
        }];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.type = @"1";//默认音频
    self.historyMutArray = [[DataBase sharedDataBase] getAllPerson];
    self.historyMutArray = (NSMutableArray *)[[self.historyMutArray reverseObjectEnumerator] allObjects];


    [self.collectionView registerClass:[LSZSearchCollectionViewCell class] forCellWithReuseIdentifier:@"LSZSearchCollectionViewCell"];
    [self.tableViewHistorical registerClass:[LSZSearchHistoricalTableViewCell class] forCellReuseIdentifier:@"LSZSearchHistoricalTableViewCell"];
    [self setSearchResults];

    self.tableViewResults.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        self.countPage = 1;
        //延时
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self initWithDataCountStr:self.searchString :self.type :self.countPage];
            [self.tableViewResults.mj_header endRefreshing];
        });
    }];
    self.tableViewResults.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        self.countPage++;
        //延时
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self initWithDataCountStr:self.searchString :self.type :self.countPage];
            [self.tableViewResults.mj_footer endRefreshing];
        });
    }];
    self.mutArrayContent = [[NSMutableArray alloc]init];
}
-(UITableView *)tableViewHistorical
{
    if (_tableViewHistorical == nil) {
        _tableViewHistorical = [[UITableView alloc]initWithFrame:CGRectMake(0 , CGRectGetMaxY(_collectionView.frame), ScreenWidth, ScreenHeight-CGRectGetMaxY(_collectionView.frame)) style:UITableViewStylePlain];
        _tableViewHistorical.delegate = self;
        _tableViewHistorical.dataSource = self;
        _tableViewHistorical.estimatedRowHeight =0;
        _tableViewHistorical.estimatedSectionFooterHeight =0;
        _tableViewHistorical.estimatedSectionHeaderHeight =0;
        _tableViewHistorical.separatorInset = UIEdgeInsetsMake(0, 20, 0, 20);
        _tableViewHistorical.separatorColor = divider;
        _tableViewHistorical.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
        [self.view addSubview:_tableViewHistorical];
    }
    return _tableViewHistorical;
}
-(UICollectionView *)collectionView
{
    if (_collectionView == nil) {
        EqualSpaceFlowLayout *flowLayout = [[EqualSpaceFlowLayout alloc] init];
        flowLayout.delegate = self;
         _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) collectionViewLayout:flowLayout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        // 是否显示垂直方向指示标, 继承于UIScrollView, 他的方法可以调用
        _collectionView.showsVerticalScrollIndicator = NO;
        [self.view addSubview:_collectionView];
    }
    return _collectionView;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    LSZSearchCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"LSZSearchCollectionViewCell" forIndexPath:indexPath];

    LSZSearchKeyMg * mg = nil;
    mg = self.SearchKeyMg.mutMgArray[indexPath.row];

    cell.labelTitle.text = [NSString stringWithFormat:@"%@",mg.title];
    NSString * strTitle = [NSString stringWithFormat:@"%@",mg.title];
    CGFloat widthHeight;
    if (ScreenWidth == 320) {
        //5
        widthHeight = [LSZSpecialPackaging caculateWidthOfText:1000 height:25 font:13.5 :strTitle];
    }else if(ScreenWidth == 375){
        // 6 7
        widthHeight = [LSZSpecialPackaging caculateWidthOfText:1000 height:29 font:14 :strTitle];
    }else{
        //plus
        widthHeight = [LSZSpecialPackaging caculateWidthOfText:1000 height:33 font:14.5 :strTitle];
    }
    CGRect rect = cell.labelTitle.frame;
    rect.size.width = widthHeight;
    cell.labelTitle.frame = rect;
    if (indexPath.row == self.SearchKeyMg.mutMgArray.count-1) {
         if (iPhoneX) {
             self.collectionView.frame = CGRectMake(0, 0, ScreenWidth, CGRectGetMaxY(cell.frame)+cell.frame.size.height+80);
         }else{
             self.collectionView.frame = CGRectMake(0, 0, ScreenWidth, CGRectGetMaxY(cell.frame)+cell.frame.size.height+50);
         }
         self.tableViewHistorical.frame = CGRectMake(0 , CGRectGetMaxY(_collectionView.frame), ScreenWidth, ScreenHeight-CGRectGetMaxY(_collectionView.frame));
    }
     return cell;
}
#pragma mark - 设置每个单元格的大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    LSZSearchKeyMg * mg = nil;
    mg = self.SearchKeyMg.mutMgArray[indexPath.row];
    NSString * strTitle = [NSString stringWithFormat:@"%@",mg.title];
    CGFloat widthHeight;
    if (ScreenWidth == 320) {
        //5
        widthHeight = [LSZSpecialPackaging caculateWidthOfText:1000 height:25 font:13.5 :strTitle];
        return CGSizeMake(widthHeight,25);
    }else if(ScreenWidth == 375){
        // 6 7
        widthHeight = [LSZSpecialPackaging caculateWidthOfText:1000 height:29 font:14 :strTitle];
        return CGSizeMake(widthHeight,29);
    }else {
        //plus
        widthHeight = [LSZSpecialPackaging caculateWidthOfText:1000 height:33 font:14.5 :strTitle];
        return CGSizeMake(widthHeight,33);
    }
}
//设置单元格间的横向间距
- (CGFloat) collectionView:(UICollectionView *)collectionView
                    layout:(UICollectionViewLayout *)collectionViewLayout
minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 10.0f;
}
 // 设置每个分区返回多少item
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return  self.SearchKeyMg.mutMgArray.count;
}
// 设置集合视图有多少个分区
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
// 点击item触发的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    self.countPage = 1;
    LSZSearchKeyMg * mg = nil;
    mg = self.SearchKeyMg.mutMgArray[indexPath.row];
    self.searchString = mg.title;
    self.textFieldSearch.text = self.searchString;
    [self searchCount:self.searchString :self.type :self.countPage];
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}
-(void)searchCount :(NSString *)countStr :(NSString *)type  :(NSInteger)countPage
{
     //加入历史记录
    self.searchString = countStr;
    
    NSString *name = countStr;
    Person *person = [[Person alloc] init];
    person.name = name;
    [[DataBase sharedDataBase] addPerson:person];
    self.historyMutArray = [[DataBase sharedDataBase] getAllPerson];
    self.historyMutArray = (NSMutableArray *)[[self.historyMutArray reverseObjectEnumerator] allObjects];
    [self.tableViewHistorical reloadData];

    [self initWithDataCountStr:countStr :type :countPage];
}
- (void)jiuyueAndxinyueData:(NSDictionary *)dictionary {
    [self SearchResultsNoHidden];
    NSArray *titleArray = dictionary[@"title"];
    NSArray *contentArray = dictionary[@"content"];
    NSMutableArray *tmpArray = [NSMutableArray array];
    for (NSInteger i = 0; i < titleArray.count; i++) {
        NSString *titleStr = titleArray[i];
        NSString *contentStr = contentArray[i];
        LSZSearchKeyContentMg *mg = [LSZSearchKeyContentMg new];
        mg.title = titleStr;
        mg.content = contentStr;
        [tmpArray addObject:mg];
    }
    [self.mutArrayContent removeAllObjects];
    self.mutArrayContent = tmpArray;
    [vcResults removeFromSuperview];

    if (self.mutArrayContent.count == 0) {
        self.tableViewResults.mj_footer.hidden = YES;
        [self resultsView];
    }else{
        self.tableViewResults.mj_footer.hidden = NO;
    }
    [self.tableViewResults reloadData];
}
#pragma mark - 空数据的展示
-(void)resultsView
{
    vcResults = [[LSZEmptyDataVC alloc]init];
    [vcResults showWithView:self.tableViewResults];
}
-(void)initWithDataCountStr:(NSString *)countStr  :(NSString *)type :(NSInteger)countPage
{
    if ([type isEqualToString:@"-1"]) {
        NSDictionary *oldDictionary = [[TheHomeManager shareTheHomeManager] searchOldAllWithStr:countStr];
        [self jiuyueAndxinyueData:oldDictionary];
        return;
    }
    if ([type isEqualToString:@"0"]) {
        NSDictionary *newsDictionary = [[TheHomeManager shareTheHomeManager] searchNewAllWithStr:countStr];
        [self jiuyueAndxinyueData:newsDictionary];
        return;
    }
    [LSZRequestResolutionDic initWithSearchKeyContent:countStr type:type page:[NSString stringWithFormat:@"%zd",countPage] :^(BOOL isOK, NSString * Str, LSZSearchKeyContentManager * mg) {
        if (isOK == YES) {
            [self SearchResultsNoHidden];
            [vcResults removeFromSuperview];
            if (countPage == 1) {
                [self.mutArrayContent removeAllObjects];
                [self.mutArrayContent addObjectsFromArray:mg.mutMgArray];
                if (self.mutArrayContent.count == 0) {
                    self.tableViewResults.mj_footer.hidden = YES;
                    [self resultsView];
                }else{
                    self.tableViewResults.mj_footer.hidden = NO;
                }
            }else{
                [self.mutArrayContent addObjectsFromArray:mg.mutMgArray];
                if (mg.mutMgArray.count == 0) {
                    self.countPage = self.countPage-1;
                    self.tableViewResults.mj_footer.hidden = YES;
                 }else{
                     self.tableViewResults.mj_footer.hidden = NO;
                }
            }
            if(mg.mutMgArray.count == 0){
                [self.tableViewResults.mj_footer endRefreshingWithNoMoreData];
            }
            [self.tableViewResults reloadData];
        }else{
            [self setStringWarning:Str];
            if (countPage ==1) {
                self.mutArrayContent = [[NSMutableArray alloc]init];
                [self.tableViewResults reloadData];
            }
        }
    }];
}
-(void)SearchResultsNoHidden
{
    self.viewTop.hidden = NO;
    self.tableViewResults.hidden = NO;
    [self.tableViewResults reloadData];
}
-(void)setSearchResults
{
    self.viewTop = [[UIView alloc]initWithFrame:CGRectMake(0,NAVIGATION_BAR_HEIGHT, ScreenWidth, 39)];
    self.viewTop.backgroundColor = [UIColor whiteColor];
    [self.viewTop.layer setBorderWidth:1];
    self.viewTop.hidden = YES;
    [self.viewTop.layer setBorderColor:[UIColor whiteColor].CGColor];
    [self.view addSubview:self.viewTop];
    NSArray * array = @[@"音频",@"文章",@"视频",@"旧约",@"新约"];
    for (int i = 0; i<array.count; i++) {
        UIButton * button = [[UIButton alloc]initWithFrame:CGRectMake(i%(array.count)*60, 0, 60, self.viewTop.frame.size.height)];
        button.titleLabel.font = FONT_15;
        button.tag = i;
        [button addTarget:self action:@selector(clickButSeare:) forControlEvents:UIControlEventTouchUpInside];
        [button setTitle:[NSString stringWithFormat:@"%@",array[i]] forState:UIControlStateNormal];
        [button setTitleColor:RGBColor(51, 51, 51) forState:UIControlStateNormal];
        [self.viewTop addSubview:button];
        if (i == array.count-1) {
            self.labelRed = [[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(button.frame)-2,60, 1)];
            self.labelRed.backgroundColor = [UIColor redColor];
            [self.viewTop addSubview:self.labelRed];
        }
    }
    self.tableViewResults =[[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.viewTop.frame), ScreenWidth, ScreenHeight-CGRectGetMaxY(self.viewTop.frame)) style:UITableViewStylePlain];
    self.tableViewResults.dataSource = self;
    self.tableViewResults.delegate = self;
    self.tableViewResults.hidden = YES;
    self.tableViewResults.estimatedRowHeight = 0;
    self.tableViewResults.estimatedSectionFooterHeight = 0;
    self.tableViewResults.estimatedSectionHeaderHeight = 0;
    self.tableViewResults.separatorInset = UIEdgeInsetsMake(0, 20, 0, 20);
    self.tableViewResults.separatorColor = divider;
    self.tableViewResults.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    [self.view addSubview:self.tableViewResults];
    [self.tableViewResults registerClass:[LSZSearchResultsTableViewCell class] forCellReuseIdentifier:@"LSZSearchResultsTableViewCell"];
    [self.tableViewResults registerClass:[LCShengJingSearchResultsCell class] forCellReuseIdentifier:@"ShengJingSearchResultsCell"];
    [self.tableViewResults registerClass:[LSZAudioRearchTableViewCell class] forCellReuseIdentifier:@"LSZAudioRearchTableViewCell"];
}
-(void)setStringWarning:(NSString *)str
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeText;//枚举类型不同的效果
    hud.label.text= [NSString stringWithFormat:@"%@",str];
    [self performSelector:@selector(hiddenMBAction) withObject:nil afterDelay:1.0];
}
-(void)hiddenMBAction
{
    [MBProgressHUD hideHUDForView:self.view animated:YES];
}
@end
